var Crypto = require('crypto-js')
var WXBizDataCrypt = require('../utils/RdWXBizDataCrypt')
import { apiBaseUrl, openBaseUrl } from './config.js'
// 获取token
export function getToken() {
  if (uni.getStorageSync('token')) {
    return uni.getStorageSync('token')
  } else {
    return 'token is null'
  }
}
export function getPhone(encryptedData,iv){
  const pc = new WXBizDataCrypt('wxdcf1b1745fa82479', getSessionKey())
  return pc.decryptData(encryptedData, iv)
}
// 存储openId
export function setOpenId(openid,companyCode = '0') {
  console.log(`储存openId`+'openid'+companyCode, openid)
  uni.setStorageSync('openid'+companyCode, openid)
}
// 获取openId
export function getOpenId(companyCode = '0') {
  console.log(`获取openId`+companyCode)
  return uni.getStorageSync('openid'+companyCode)
}
// 存储session_key
export function setSessionKey(openid,companyCode = '0') {
  uni.setStorageSync('sessionKey'+companyCode, openid)
}
//获取session_key
export function getSessionKey(companyCode = '0') {
  return uni.getStorageSync('sessionKey'+companyCode)
}



// 存储token
export function setToken(token) {
  uni.setStorageSync('token', token)
}

// 存储用户信息
export function setUserInfo(userInfo) {
  user = userInfo
  uni.setStorageSync('userInfo',JSON.stringify(user))
}

let user = null;
// 获取用户信息
export function getUserInfo() {
  if(user)return user;
  const userInfo = uni.getStorageSync('userInfo');
  if (!userInfo)return null;
  user = JSON.parse(userInfo)
  return user;
}

// 消息提示
export function message(title) {
  uni.showToast({
    icon: 'none',
    title: title,
  })
}
//获取屏幕大小
export function getScreen(title) {
  let width,height
  uni.getSystemInfo({
    success:function (res) {
      width = res.windowWidth
      height = res.windowHeight
    }
  })
  return {width,height}
}
//计算经纬度之间距离
export function getDistance(lat1, lng1, lat2, lng2) {
  lat1 = lat1 || 0;
  lng1 = lng1 || 0;
  lat2 = lat2 || 0;
  lng2 = lng2 || 0;

  var rad1 = lat1 * Math.PI / 180.0;
  var rad2 = lat2 * Math.PI / 180.0;
  var a = rad1 - rad2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  var r = 6378137;
  var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));

  return distance;
}
//保存图片
export function saveImage(e){
  return new Promise((resolve, reject) => {

    uni.uploadFile({
      url: apiBaseUrl + '/api/common/uploadImage',
      filePath: e,
      name: 'file',
      header: {
        Authorization: getToken()
      },
      formData: {
        'user': 'test'
      },
      success: (res) => {
        console.log(res,JSON.parse(res.data).status)
        const mg=JSON.parse(res.data)
        if (mg.status===200) {
          const { path} = mg.data
        resolve(path)
          // uni.showToast({title:mg.msg,icon:'none'})
        }else{
          uni.showToast({title:mg.msg,icon:'none'})
        }

      }
    });
  })
}
//防抖
export const debounce = (fn,time = 300,...args)=>{
  let timeOut = null
  return function (){
    timeOut && clearTimeout(timeOut)
    timeOut = setTimeout(()=>{
      fn.bind(this)(...args)
    },time)
  }
}
//商品图片处理
export function setImage(str){
  let imagePath = ' '
  if (str){
    try {
      const list = JSON.parse(str)
      if (list)
      imagePath = list[0].path
    }catch (e) {
      return imagePath
    }
  }
  return imagePath
}

//小程序名称公司logo

export function getCompanyLogo(appid){
  const companyList = {
    //妙配
    wxdcf1b1745fa82479: 'https://www.zjjqf.cn/file/static/MPlogo.png',
    wx892dd4dec149aff9: 'https://www.zjjqf.cn/file/static/103logo.png',
    //瀚鼎
    wxd3ab5c1fa0f287fb: 'https://www.zjjqf.cn/file/static/104logo.png',
    wx2293459a335dd463: 'https://www.zjjqf.cn/file/static/108logo.png',
    //山海直达
    wx089f76659a84f8dd: 'https://www.zjjqf.cn/file/static/shzdlogo.png',
    //
    wxaead918705506e63: 'https://www.zjjqf.cn/file/static/018logo.png',
    //滢盛
    wx555f81f7357a24bc:'https://www.zjjqf.cn/file/static/yslogo.jpg'
  }
  if(Object.keys(companyList).includes(appid))return companyList[appid]
  return 'https://www.zjjqf.cn/file/static/MPlogo.png'
}

//获取当天日期
export function curDate(){
  const date = new Date()
  let  month = date.getMonth() + 1
  let day = date.getDate()
  if (month< 10 )month = '0'+month
  if (day< 10 )day = '0'+day
  return `${date.getFullYear()}-${month}-${day}`
}

//格式化日期
export function formateDate(timestamp){
  const date = new Date(timestamp)
  let  month = date.getMonth() + 1
  let day = date.getDate()
  if (month< 10 )month = '0'+month
  if (day< 10 )day = '0'+day
  return `${date.getFullYear()}-${month}-${day}`
}

export function curTime(){
  var currentDate = new Date();
  var year = currentDate.getFullYear();
  var month = ('0' + (currentDate.getMonth() + 1)).slice(-2);
  var day = ('0' + currentDate.getDate()).slice(-2);
  var hours = ('0' + currentDate.getHours()).slice(-2);
  var minutes = ('0' + currentDate.getMinutes()).slice(-2);
  const seconds = ('0' + currentDate.getSeconds()).slice(-2);
  var formattedDate = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
  return formattedDate
}
let recentUsed = []
export function getRecentUsed(){
  if (recentUsed.length === 0){
    const recentUsedJson = uni.getStorageSync('recentUsed')
    if (recentUsedJson)recentUsed  = recentUsedJson;
  }
  return recentUsed
}
//最近使用的功能缓存
export function setRecentUsed(obj){
  const index = recentUsed.findIndex(item=>item.name===obj.name)
  if(~index){
    const item = recentUsed.splice(index,1)
    return recentUsed.unshift(item[0])
  }
  if (recentUsed.length>4){
    recentUsed.pop()
  }
  recentUsed.unshift(obj)
  uni.setStorageSync('recentUsed',recentUsed)
}